package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.PageResult;
import com.tju.ocean_ecology_website.dto.TeamDetailDTO;
import com.tju.ocean_ecology_website.dto.TeamJoinResponseDTO;
import com.tju.ocean_ecology_website.dto.TeamListItemDTO;
import com.tju.ocean_ecology_website.dto.VolunteerTeamQueryDTO;
import com.tju.ocean_ecology_website.entity.Activity;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.entity.VolunteerTeam;
import com.tju.ocean_ecology_website.entity.VolunteerTeamMember;
import com.tju.ocean_ecology_website.mapper.UserMapper;
import com.tju.ocean_ecology_website.service.ActivityService;
import com.tju.ocean_ecology_website.service.VolunteerTeamMemberService;
import com.tju.ocean_ecology_website.service.VolunteerTeamService;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.Comparator;

/**
 * 志愿者队伍控制器
 */
@RestController
@RequestMapping("/api/volunteer")
public class VolunteerTeamController {

    @Resource
    private VolunteerTeamService volunteerTeamService;

    @Resource
    private VolunteerTeamMemberService volunteerTeamMemberService;

    @Resource
    private ActivityService activityService;

    @Resource
    private UserMapper userMapper;

    /**
     * 获取志愿者队伍列表
     *
     * @param queryDTO 查询参数
     * @return 志愿者队伍列表
     */
    @GetMapping("/teams")
    public ResponseEntity<ApiResponse<PageResult<TeamListItemDTO>>> getVolunteerTeams(VolunteerTeamQueryDTO queryDTO) {
        // 获取当前用户ID
        final Long currentUserId = getCurrentUserId();

        // 创建查询条件
        VolunteerTeam teamQuery = new VolunteerTeam();

        // 如果只查询我加入的队伍
        final List<Long> myTeamIds;
        if (Boolean.TRUE.equals(queryDTO.getMine())) {
            // 查询我加入的队伍ID列表
            VolunteerTeamMember memberQuery = new VolunteerTeamMember();
            memberQuery.setUserId(currentUserId);
            List<VolunteerTeamMember> myTeams = volunteerTeamMemberService.queryAll(memberQuery);
            myTeamIds = myTeams.stream()
                    .map(VolunteerTeamMember::getTeamId)
                    .collect(Collectors.toList());

            // 如果没有加入任何队伍，返回空列表
            if (myTeamIds.isEmpty()) {
                PageResult<TeamListItemDTO> emptyResult = new PageResult<>();
                emptyResult.setList(Collections.emptyList());
                emptyResult.setTotal(0L);
                emptyResult.setPage(queryDTO.getPage());
                emptyResult.setPageSize(queryDTO.getPageSize());
                emptyResult.setPages(0);
                return ResponseEntity.ok(ApiResponse.success(emptyResult));
            }
        } else {
            myTeamIds = Collections.emptyList(); // 如果不是只查询我加入的队伍，初始化为空列表
        }

        // 设置关键词搜索
        // 注意：这里简化处理，实际应该在DAO层添加模糊查询
        if (queryDTO.getKeyword() != null && !queryDTO.getKeyword().isEmpty()) {
            // 在实际实现中，应该添加模糊查询
        }

        // 查询队伍列表
        Page<VolunteerTeam> teamPage = volunteerTeamService.queryByPage(teamQuery, queryDTO.toPageRequest());

        // 过滤我加入的队伍
        List<VolunteerTeam> filteredTeams = teamPage.getContent();
        if (Boolean.TRUE.equals(queryDTO.getMine()) && !myTeamIds.isEmpty()) {
            filteredTeams = filteredTeams.stream()
                    .filter(team -> myTeamIds.contains(team.getId()))
                    .collect(Collectors.toList());
        }

        // 查询我在每个队伍中的角色
        Map<Long, String> teamRoleMap = new HashMap<>();
        for (VolunteerTeam team : filteredTeams) {
            VolunteerTeamMember memberQuery = new VolunteerTeamMember();
            memberQuery.setTeamId(team.getId());
            memberQuery.setUserId(currentUserId);
            List<VolunteerTeamMember> members = volunteerTeamMemberService.queryAll(memberQuery);
            if (!members.isEmpty()) {
                VolunteerTeamMember member = members.get(0);
                teamRoleMap.put(team.getId(), member.getRole() == 1 ? "leader" : "member");
            }
        }

        // 转换为DTO
        List<TeamListItemDTO> teamDTOs = filteredTeams.stream()
                .map(team -> {
                    // 查询队伍成员数量
                    VolunteerTeamMember memberQuery = new VolunteerTeamMember();
                    memberQuery.setTeamId(team.getId());
                    List<VolunteerTeamMember> members = volunteerTeamMemberService.queryAll(memberQuery);

                    // 查询队伍活动数量
                    Activity activityQuery = new Activity();
                    activityQuery.setTeamId(team.getId());
                    List<Activity> activities = activityService.queryAll(activityQuery);

                    // 计算队伍总服务时长（简化处理，实际应该有专门的统计接口）
                    int totalHours = 0;

                    // 获取我在队伍中的角色
                    String role = teamRoleMap.getOrDefault(team.getId(), null);

                    // 构建标签列表（简化处理，实际应该有标签表）
                    List<String> tags = new ArrayList<>();
                    if (team.getTags() != null && !team.getTags().isEmpty()) {
                        tags = Arrays.asList(team.getTags().split(","));
                    }

                    return TeamListItemDTO.builder()
                            .id(team.getId())
                            .name(team.getName())
                            .description(team.getDescription())
                            .avatar(team.getAvatar())
                            .isVerified(team.getVerified() == 1)
                            .role(role)
                            .memberCount(members.size())
                            .activityCount(activities.size())
                            .totalHours(totalHours)
                            .tags(tags)
                            .build();
                })
                .collect(Collectors.toList());

        // 创建分页结果
        PageResult<TeamListItemDTO> pageResult = new PageResult<>();
        pageResult.setList(teamDTOs);
        pageResult.setTotal(teamPage.getTotalElements());
        pageResult.setPage(queryDTO.getPage());
        pageResult.setPageSize(queryDTO.getPageSize());
        pageResult.setPages(teamPage.getTotalPages());

        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 获取队伍详情
     *
     * @param id 队伍ID
     * @return 队伍详情
     */
    @GetMapping("/teams/{id}")
    public ResponseEntity<ApiResponse<TeamDetailDTO>> getTeamDetail(@PathVariable("id") Long id) {
        // 获取当前用户ID
        final Long currentUserId = getCurrentUserId();

        // 查询队伍信息
        VolunteerTeam team = volunteerTeamService.queryById(id);
        if (team == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }

        // 查询队伍成员
        VolunteerTeamMember memberQuery = new VolunteerTeamMember();
        memberQuery.setTeamId(id);
        List<VolunteerTeamMember> members = volunteerTeamMemberService.queryAll(memberQuery);

        // 查询队长信息
        VolunteerTeamMember leaderQuery = new VolunteerTeamMember();
        leaderQuery.setTeamId(id);
        leaderQuery.setRole(1); // 队长角色
        List<VolunteerTeamMember> leaders = volunteerTeamMemberService.queryAll(leaderQuery);
        TeamDetailDTO.TeamMemberDTO leaderInfo = null;
        if (!leaders.isEmpty()) {
            VolunteerTeamMember leader = leaders.get(0);
            User leaderUser = userMapper.findById(leader.getUserId());
            if (leaderUser != null) {
                leaderInfo = TeamDetailDTO.TeamMemberDTO.builder()
                        .id(leaderUser.getId())
                        .name(leaderUser.getUsername())
                        .avatar(leaderUser.getAvatar())
                        .role("leader")
                        .joinTime(leader.getJoinTime())
                        .build();
            }
        }

        // 查询我在队伍中的角色
        String myRole = null;
        for (VolunteerTeamMember member : members) {
            if (member.getUserId().equals(currentUserId)) {
                myRole = member.getRole() == 1 ? "leader" : "member";
                break;
            }
        }

        // 查询队伍活动
        Activity activityQuery = new Activity();
        activityQuery.setTeamId(id);
        List<Activity> activities = activityService.queryAll(activityQuery);

        // 获取最近的活动（最多5个）
        List<Activity> recentActivities = activities.stream()
                .sorted(Comparator.comparing(Activity::getStartTime).reversed())
                .limit(5)
                .collect(Collectors.toList());

        // 转换为活动DTO
        List<TeamDetailDTO.TeamActivityDTO> activityDTOs = recentActivities.stream()
                .map(activity -> TeamDetailDTO.TeamActivityDTO.builder()
                        .id(activity.getId())
                        .title(activity.getTitle())
                        .date(activity.getStartTime())
                        .participantCount(activity.getCurrentParticipants())
                        .build())
                .collect(Collectors.toList());

        // 转换成员列表
        List<TeamDetailDTO.TeamMemberDTO> memberDTOs = members.stream()
                .map(member -> {
                    User user = userMapper.findById(member.getUserId());
                    if (user == null) return null;

                    return TeamDetailDTO.TeamMemberDTO.builder()
                            .id(user.getId())
                            .name(user.getUsername())
                            .avatar(user.getAvatar())
                            .role(member.getRole() == 1 ? "leader" : "member")
                            .joinTime(member.getJoinTime())
                            .build();
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 构建标签列表
        List<String> tags = new ArrayList<>();
        if (team.getTags() != null && !team.getTags().isEmpty()) {
            tags = Arrays.asList(team.getTags().split(","));
        }

        // 计算队伍总服务时长（简化处理，实际应该有专门的统计接口）
        int totalHours = 0;

        // 构建队伍详情DTO
        TeamDetailDTO teamDetailDTO = TeamDetailDTO.builder()
                .id(team.getId())
                .name(team.getName())
                .description(team.getDescription())
                .avatar(team.getAvatar())
                .banner(team.getBanner())
                .isVerified(team.getVerified() == 1)
                .createTime(team.getCreateTime())
                .leaderInfo(leaderInfo)
                .myRole(myRole)
                .memberCount(members.size())
                .activityCount(activities.size())
                .totalHours(totalHours)
                .tags(tags)
                .members(memberDTOs)
                .recentActivities(activityDTOs)
                .build();

        return ResponseEntity.ok(ApiResponse.success(teamDetailDTO));
    }

    /**
     * 加入队伍
     *
     * @param id 队伍ID
     * @return 加入结果
     */
    @PostMapping("/teams/{id}/join")
    public ResponseEntity<ApiResponse<TeamJoinResponseDTO>> joinTeam(@PathVariable("id") Long id) {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询队伍信息
        VolunteerTeam team = volunteerTeamService.queryById(id);
        if (team == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }

        // 检查是否已经是队伍成员
        VolunteerTeamMember memberQuery = new VolunteerTeamMember();
        memberQuery.setTeamId(id);
        memberQuery.setUserId(currentUserId);
        List<VolunteerTeamMember> existingMembers = volunteerTeamMemberService.queryAll(memberQuery);
        if (!existingMembers.isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "您已经是该队伍的成员"));
        }

        // 创建新的队伍成员记录
        VolunteerTeamMember newMember = new VolunteerTeamMember();
        newMember.setTeamId(id);
        newMember.setUserId(currentUserId);
        newMember.setRole(0); // 普通成员
        newMember.setStatus(0); // 待审核
        Date now = new Date();
        newMember.setJoinTime(now);
        newMember.setCreateTime(now);
        newMember.setUpdateTime(now);

        // 保存队伍成员记录
        volunteerTeamMemberService.insert(newMember);

        // 构建响应
        TeamJoinResponseDTO responseDTO = TeamJoinResponseDTO.builder()
                .status("pending")
                .applyTime(now)
                .build();

        return ResponseEntity.ok(ApiResponse.success(responseDTO, "申请已提交，请等待审核"));
    }

    /**
     * 获取当前登录用户的ID
     *
     * @return 当前用户ID
     */
    private Long getCurrentUserId() {
        // 从 SecurityContextHolder 获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取用户名
            String username = authentication.getName();
            // 通过用户名查询用户信息
            User user = userMapper.findByUsername(username);
            if (user != null) {
                return user.getId();
            }
        }
        // 如果无法获取用户信息，抛出异常
        throw new RuntimeException("未能获取当前用户信息，请确保用户已登录");
    }
}
